package com.android.nodejs.livejs.utils;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

public class CommonUtil {
    
    /**
     * get resize bitmap
     * 
     * @param bm
     * @param newHeight
     * @param newWidth
     * @return
     */
	public static Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
		int width = bm.getWidth();
		int height = bm.getHeight();
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height,
				matrix, false);
		return resizedBitmap;
	}

	public static Bitmap getResizedBitmap(Context context, Uri uriOfBitmap, int size) throws FileNotFoundException {
		BitmapFactory.Options o = new BitmapFactory.Options();
		o.inJustDecodeBounds = true;
		BitmapFactory.decodeStream(context.getContentResolver().openInputStream(uriOfBitmap), null, o);
		final float REQUIRED_SIZE = size;
		int width_tmp = o.outWidth, height_tmp = o.outHeight;
		int scale = 1;
		while (true) {
			if (width_tmp / 2 < REQUIRED_SIZE && height_tmp / 2 < REQUIRED_SIZE) {
				break;
			}
			width_tmp /= 2;
			height_tmp /= 2;
			scale *= 2;
		}
		BitmapFactory.Options o2 = new BitmapFactory.Options();
		o2.inSampleSize = scale;
		return BitmapFactory.decodeStream(context.getContentResolver().openInputStream(uriOfBitmap), null, o2);
	}

	/**
	 * check network available
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isNetworkAvailable(Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity != null) {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}

	/**
	 * get bytes
	 * 
	 * @param bitmap
	 * @return
	 */
	public static byte[] getBytes(Bitmap bitmap) {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		bitmap.compress(CompressFormat.PNG, 0, stream);
		return stream.toByteArray();
	}

	/**
	 * get Image bitmap
	 * 
	 * @param image
	 * @return
	 */
	public static Bitmap getImage(byte[] image) {
		return BitmapFactory.decodeByteArray(image, 0, image.length);
	}

    /**
     * show toast
     * 
     * @param context
     * @param message
     */
    public static void toastNotify(Context context, String message) {
        int duration = Toast.LENGTH_SHORT;
        Toast toast = Toast.makeText(context, message, duration);
        toast.show();
    }

    /**
     * show dialog
     * 
     * @param context
     * @param message
     */
    public static void dialogNotify(Context context, String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setMessage(message).setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });
        AlertDialog alert = builder.create();
        alert.show();
    }

    /**
     * Convert a String to md5
     * 
     * @param password
     * @return String
     */
    public static String convertToMD5(String password) {
        MessageDigest md;
        StringBuffer sb = new StringBuffer();
        try {
            md = MessageDigest.getInstance("MD5");
            md.update(password.getBytes());
            byte byteData[] = md.digest();
            for (int i = 0; i < byteData.length; i++) {
                sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
    
    /**
     * convert JSON Date to string date
     * 
     * @param srcDate
     * @return String
     */
    public static String dateToString(String srcDate) {
        String desDate = null;
        String[] tmp = srcDate.split("T");
        String[] date = tmp[0].split("-");
        desDate = date[0] + "/" + date[1] + "/" + date[2];
        return desDate;
    }
    
    /**
     * Get the current time of the system
     * 
     * @return String
     */
    public static String getSysTime() {
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR);
        int minute = calendar.get(Calendar.MINUTE);
        int am_pm = calendar.get(Calendar.AM_PM);
        if (am_pm == 1) {
            return "" + hour + ":" + minute + "PM";
        } else {
            return "" + hour + ":" + minute + "AM";
        }
    }
    
    /**
     * Get the current date time of the system
     * 
     * @return String
     */
    public static String getSysDateTime() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR);
        int minute = calendar.get(Calendar.MINUTE);
        int am_pm = calendar.get(Calendar.AM_PM);
        if (am_pm == 1) {
            return "" + year + "-" + month + "-" + day + " " + hour + ":" + minute + "PM";
        } else {
            return "" + year + "-" + month + "-" + day + " " + hour + ":" + minute + "AM";
        }
    }
    
    /**
     * Convert String from Server response to JSON object
     * 
     * @param src
     * @return JSONObject
     */
    public static JSONObject convertToJSONObject(String src) {
        try {
            JSONObject json = new JSONObject(src);
            return json;
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * convert Array String JSON from server response to list JSON object
     * 
     * @param src
     * @return List<JSONObject>
     */
    public static List<JSONObject> convertToListJSONObject(String src) {
        List<JSONObject> listJson = new ArrayList<JSONObject>();
        try {
            JSONArray jArr = new JSONArray(src);
            for (int i = 0; i < jArr.length(); i++) {
                JSONObject json = jArr.getJSONObject(i);
                listJson.add(json);
            }
            return listJson;
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * split String Server Response
     * 
     * @param src
     * @return String[]
     */
    public static String[] strServerResponse(String src) {
        String[] des = null;
        des = src.split("##");
        return des;
    }
    
    /**
     * hide virtual keyboard in android
     * 
     * @param v
     */
    public static void hideVirtualKeyboard(View v) {
        InputMethodManager imm = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
    }
}
